<template>
  <div class="app-container bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view/>
    </transition>
    <el-card v-if="isShow" class="box-1">
      <div class="header-reamrk">
        <el-row v-if="showType===0">由于您的客户数量较大,已为您的客户订单做了缓存优化(每两小时更新一次数据)已给您更顺畅的浏览体验,如需实时代付客户的订单,请您
          <el-button type="text" @click="bindChangeType(1)">点击获取实时代付订单</el-button>
          操作.<br>目前仅支持搜索当天订单号,需使用搜索功能时请清除日期选择.
        </el-row>
        <el-row v-else>本页面支持代付您自己的订单，代付后如需查看详情，请前往
          <el-button type="text" @click="bindChangeType(0)">订单管理</el-button>
        </el-row>
      </div>
      <div class="header">
        <div>
          <el-button v-if="queryMatch(267)" type="primary" class="bg-green" style="margin-right: 10px;" @click="toPayOrders">代付</el-button>
          <el-select v-model="searchTerms.status" placeholder="状态" clearable @change="getData">
            <el-option value="1" label="未支付"/>
            <el-option value="2" label="已支付"/>
            <el-option value="3" label="发货中"/>
            <el-option value="4" label="已发货"/>
            <el-option value="5" label="发货失败"/>
            <el-option value="6" label="已退款"/>
            <el-option value="7" label="已关单"/>
            <el-option value="8" label="订单过期"/>
            <el-option value="9" label="订单已失效"/>
            <el-option value="10" label="产品已失效"/>
            <el-option value="11" label="代付拒绝"/>
            <el-option value="12" label="支付中"/>
          </el-select>
          <el-select v-model="searchTerms.payerMode" placeholder="支付方式" clearable @change="getData">
            <el-option value="0" label="自付"/>
            <el-option value="1" label="代付"/>
          </el-select>
          <el-select v-model="searchTerms['sales_uin']" clearable filterable class="select" placeholder="业务员" @change="getData">
            <el-option v-for="(item, index) in salerList" :key="index" :label="`业务员：${item.sales_name}`" :value="item.sales_uin"/>
          </el-select>
          <el-date-picker
            v-model="searchTerms.date"
            type="daterange"
            range-separator="-"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getData"/>
          <el-input v-model="searchTerms.searchValue" placeholder="请输入内容" class="search-input" @change="getData">
            <el-select slot="prepend" v-model="searchTerms.searchSelected" class="search-select">
              <el-option :value="0" label="订单号"/>
              <el-option :value="1" label="客户账号"/>
              <el-option :value="2" label="客户备注"/>
              <el-option v-if="$store.getters.id===1||queryMatch(268)" :value="3" label="业务员"/>
            </el-select>
          </el-input>
          <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
          <div class="flex-1"/>
          <div v-if="queryMatch(274)">
            <el-link :underline="false" @click="submitDownload"><i class="el-icon-download"/> 下载</el-link>
            <el-link href="./#/tencent/order/download" type="primary" style="margin-left: 15px;"><i class="el-icon-document-checked"/> 查看下载记录</el-link>
          </div>
        </div>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row
                @selection-change="handleSelectionChange"
                @sort-change="handleSortChange">
        <el-table-column :selectable="selectable" type="selection" width="55" header-align="center" align="center"/>
        <el-table-column prop="creatTime" label="创建时间" min-width="160" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.creatTime?scope.row.creatTime:'--' }}
          </template>
        </el-table-column>
        <el-table-column prop="dealName" label="订单号" min-width="140" header-align="center" align="center"/>
        <el-table-column label="状态" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.dealStatus }}
          </template>
        </el-table-column>
        <el-table-column label="客户账号/备注" min-width="180" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.ownerUin?scope.row.ownerUin:'--' }}
            <div class="remarks">{{ scope.row.clientRemark }}</div>
          </template>
        </el-table-column>
        <el-table-column label="客户类型" min-width="120" header-align="center" align="center">
          <!--<template slot="header" slot-scope="scope">
            <el-dropdown @command="handleCustomerTypeCommand">
              <span class="el-dropdown-link">
                客户类型<i class="el-icon-arrow-down el-icon&#45;&#45;right"/>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="">全部</el-dropdown-item>
                <el-dropdown-item command="new">新拓</el-dropdown-item>
                <el-dropdown-item command="assign">指定</el-dropdown-item>
                <el-dropdown-item command="old">存量</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>-->
          <template slot-scope="scope">
            {{ scope.row.clientType === 'new' ? '新拓': scope.row.clientType === 'old' ? '存量' : '指派' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="云产品" min-width="120" header-align="center" align="center"/>
        <el-table-column prop="balance" label="费用（元）" min-width="140" header-align="center" align="center">
          <template slot-scope="scope">
            <!--<span class="price">{{ (scope.row['goodsPrice']['totalCost']/100).toFixed(2) }}元</span>-->
            <span class="real-price">{{ (scope.row['goodsPrice']['realTotalCost']/100).toFixed(2) }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="isArrears" label="支付方式" min-width="100" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.payerMode==='0'?'自付':'代付' }}
          </template>
        </el-table-column>
        <el-table-column label="业务员" min-width="100" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.salesName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status==='1'&&queryMatch(267)" type="text" size="mini" @click="toPay(scope.row)">代付</el-button>
            <el-button type="text" size="mini" @click="toDetails(scope.row)">订单详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :total="total"
        :layout="($store.getters.id===1||queryMatch(269))&&!searchTerms.sales_uin?'total, prev, pager, next, jumper':'prev, next'"
        class="pagination"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>
  </div>
</template>

<script>
  import {handleSortChange, handleSizeChange, handleCurrentChange, parseTime} from '@/utils/table'

  export default {
    data() {
      return {
        isShow: true,
        showType: 0,
        searchTerms: {
          searchValue: '',
          searchSelected: 0,
          status: '',
          date: [],
          payerMode: '',
          sales_uin: ''
        },
        // 业务员列表
        salerList: [],
        // 表格相关数据
        tableMaxHeight: document.documentElement.clientHeight - 300,
        tableLoading: false,
        currentPage: 1,
        pageSize: 30,
        total: 0,
        tableData: [],
        multipleSelection: []
      }
    },
    watch: {
      $route(to) {
        if (to.name === '腾讯订单管理') {
          this.isShow = true
          this.getData()
        } else {
          this.isShow = false
        }
      }
    },
    created() {
      const date = new Date();
      const y = date.getFullYear();
      const m = date.getMonth();
      const firstDay = new Date(y, m, 1);
      parseTime(date, '{y}-{m}-{d}')
      this.searchTerms.date.push(parseTime(firstDay, '{y}-{m}-{d}'))
      this.searchTerms.date.push(parseTime(date, '{y}-{m}-{d}'))
      if (this.$route.query['customerId']) {
        this.searchTerms.searchSelected = 1;
        this.searchTerms.searchValue = this.$route.query['customerId'];
      }
      this.searchTerms.searchValue = this.$route.query.orderId || '';
      this.getSalerList();
    },
    methods: {
      handleCurrentChange, handleSizeChange, handleSortChange, parseTime,
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      selectable(row) {
        return row.status === '1';
      },
      bindChangeType(type) {
        this.showType = type;
        if (type === 1) {
          const date = new Date();
          this.searchTerms.date = [];
          const y = date.getFullYear();
          const m = date.getMonth();
          const d = date.getDate();
          const firstDay = new Date(y, m, d - 2);
          this.searchTerms.date.push(parseTime(firstDay, '{y}-{m}-{d}'))
          this.searchTerms.date.push(parseTime(date, '{y}-{m}-{d}'))
        }
        this.getData();
      },
      getData() {
        this.tableLoading = true
        let url = ''
        const data = {
          page_no: this.currentPage,
          page_size: this.pageSize,
          status: this.searchTerms.status,
          payerMode: this.searchTerms.payerMode,
          sales_uin: this.searchTerms.sales_uin
        }
        if (this.searchTerms.searchSelected === 0) {
          data.deal_names = this.searchTerms.searchValue
        } else if (this.searchTerms.searchSelected === 1) {
          data.owner_uin = this.searchTerms.searchValue
        } else if (this.searchTerms.searchSelected === 2) {
          data.client_remark = this.searchTerms.searchValue
        } else if (this.searchTerms.searchSelected === 3) {
          data.sales_name = this.searchTerms.searchValue
        }
        // 腾讯云搜索
        if (this.showType === 0) {
          url = 'tencent/selectCustomerCacheOrders'
        } else {
          url = 'tencent/selectCustomerOrders'
        }
        if (this.searchTerms.date === '' || this.searchTerms.date === null || !this.searchTerms.date || this.searchTerms.date.length === 0) {
          this.searchTerms.date = [];
          const date = new Date()
          this.searchTerms.date.push(parseTime(date, '{y}-{m}-{d}'));
          this.searchTerms.date.push(parseTime(date, '{y}-{m}-{d}'));
        }
        data.start_time = this.searchTerms.date[0] + ' 00:00:00';
        data.end_time = this.searchTerms.date[1] + ' 23:59:59';
        this.$store.dispatch('GetConnect', {url, data}).then(res => {
          this.tableData = res.data.list
          this.total = parseInt(res.data.total)
          this.tableLoading = false
        }).catch(e => {
          this.tableLoading = false
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },
      // 加载业务员列表
      getSalerList() {
        const url = 'tencent/getSaleByUser'
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.salerList = res.data;
          if (this.salerList.length > 0) {
            this.getData({});
          } else if (this.$store.getters.id === 1 || this.queryMatch(268)) {
            this.getData({});
          }
        }).catch(e => {
          this.tableLoading = false
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },
      toDetails(row) {
        this.$router.push({
          path: './details',
          query: {
            // row: JSON.stringify(row)
            deal_names: row.dealName,
            showType: this.showType
          }
        })
      },
      toPay(row) {
        this.$router.push({
          path: './pay',
          query: {
            // row: JSON.stringify(row)
            deal_names: row.dealName,
            showType: this.showType
          }
        })
      },
      toPayOrders() {
        if (this.multipleSelection.length <= 0) {
          this.$message.error('请先选择订单')
          return
        }
        this.$confirm('此操作将支付选中的订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const temp = []
          for (let i = 0; i < this.multipleSelection.length; i++) {
            temp.push({
              owner_uin: this.multipleSelection[i].ownerUin,
              deal_name: this.multipleSelection[i].dealName,
              total_price: this.multipleSelection[i]['goodsPrice']['realTotalCost']
            })
          }
          const url = 'tencent/substitutePayment'
          const data = {
            params: JSON.stringify(temp)
          };
          this.$store.dispatch('GetConnect', {url, data}).then(res => {
            this.$message.success('支付订单成功!')
            this.$router.back()
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员')
          })
        })
      },

      submitDownload() {
        const url = 'tencent/downDataAnalysis'
        const data = {
          startTime: this.searchTerms.date[0] + '00:00:00',
          endTime: this.searchTerms.date[1] + '23:59:59'
        }
        this.$store.dispatch('GetConnect', {url, data}).then(() => {
          this.$router.push('/tencent/order/download')
        }).catch(e => {
          this.$message.error('操作失败,请刷新或联系管理员')
        })
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../../styles/index.scss';

  .box-1 {
    .header-reamrk {
      padding-bottom: 15px;

      .el-row {
        border: 1px solid $panGreen;
        border-radius: 4px;
        background-color: rgba(22, 219, 195, 0.11);
        padding: 10px 12px;
        font-size: 12px;
        color: $text43;
      }

      .el-button {
        font-size: 12px;
        padding: 0 0 12px 0;
      }
    }

    .header {
      @include flex-row(center, space-between);
      padding-bottom: 15px;
      flex-wrap: wrap;

      > div {
        @include flex-row(center, flex-start);
        flex-wrap: wrap;
        width: 100%;
        >.el-select {
          margin-right: 15px;
          width: 160px;
        }
      }

      .el-date-editor {
        width: 300px;
      }

      .search-input {
        margin-left: 15px;
        width: 280px;
        .search-select{
          width: 100px;
        }
      }

      .do-btn {
        @extend .bg-green;
        margin-left: 2px;
      }
    }

    .price {
      font-size: 10px;
      color: $textGray;
      text-decoration: line-through;
      margin-right: 6px;
    }

    .real-price {
      color: $yellow;
    }
  }

  .dialog {
    .content {
      text-align: center;
    }
  }

  .el-tag {
    cursor: pointer;
  }

  .remarks {
    font-size: 12px;
    color: $textGray;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
